<template>
  <div class="cameras-container">
    <el-card class="page-card">
      <template #header>
        <div class="page-header">
          <span>摄像头监控</span>
          <el-button type="primary" @click="openAddCameraDialog">
            <el-icon><Plus /></el-icon>
            添加摄像头
          </el-button>
        </div>
      </template>
      
      <!-- 摄像头网格 -->
      <div class="cameras-grid" v-if="!loading">
        <el-card 
          v-for="camera in cameras" 
          :key="camera.id"
          class="camera-card"
          :class="{ 'camera-offline': !camera.is_active }"
        >
          <template #header class="camera-header">
            <div class="camera-info">
              <h3 class="camera-name">{{ camera.name }}</h3>
              <el-tag :type="camera.is_active ? 'success' : 'danger'" size="small">
                {{ camera.is_active ? '在线' : '离线' }}
              </el-tag>
            </div>
            <div class="camera-actions">
              <el-dropdown>
                <el-button size="small" type="text">
                  <el-icon><Setting /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="viewCameraStream(camera.id)">
                      <el-icon><View /></el-icon> 查看视频流
                    </el-dropdown-item>
                    <el-dropdown-item @click="editCamera(camera)">
                      <el-icon><Edit /></el-icon> 编辑
                    </el-dropdown-item>
                    <el-dropdown-item v-if="!camera.is_active" @click="startCamera(camera.id)">
          <el-icon><Play /></el-icon> 启动
        </el-dropdown-item>
        <el-dropdown-item v-if="camera.is_active" @click="stopCamera(camera.id)">
          <el-icon><Close /></el-icon> 停止
        </el-dropdown-item>
                    <el-dropdown-item divided @click="deleteCamera(camera.id)" type="danger">
                      <el-icon><Delete /></el-icon> 删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
          
          <!-- 摄像头预览 -->
          <div class="camera-preview">
            <img 
              :src="camera.snapshot || '/camera-placeholder.jpg'" 
              :alt="camera.name"
              @click="viewCameraStream(camera.id)"
              class="preview-image"
            />
            <div class="camera-stats">
              <div class="stat-item">
                <span class="stat-label">IP地址：</span>
                <span class="stat-value">{{ camera.ip_address || 'N/A' }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">位置：</span>
                <span class="stat-value">{{ camera.location || 'N/A' }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">今日告警：</span>
                <span class="stat-value">{{ camera.today_alerts || 0 }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </div>
      
      <!-- 加载状态 -->
      <div v-else class="loading-container">
        <el-skeleton :rows="4" animated />
      </div>
      
      <!-- 无数据状态 -->
      <div v-if="!loading && cameras.length === 0" class="empty-state">
        <el-empty description="暂无摄像头数据" />
      </div>
    </el-card>
    
    <!-- 添加/编辑摄像头对话框 -->
    <el-dialog
      v-model="cameraDialogVisible"
      :title="cameraDialogType === 'add' ? '添加摄像头' : '编辑摄像头'"
      width="500px"
    >
      <el-form
        ref="cameraFormRef"
        :model="cameraForm"
        :rules="cameraFormRules"
        label-width="100px"
      >
        <el-form-item label="摄像头名称" prop="name">
          <el-input v-model="cameraForm.name" placeholder="请输入摄像头名称" />
        </el-form-item>
        <el-form-item label="RTSP地址" prop="rtsp_url">
          <el-input v-model="cameraForm.rtsp_url" placeholder="请输入RTSP地址" />
        </el-form-item>
        <el-form-item label="IP地址" prop="ip_address">
          <el-input v-model="cameraForm.ip_address" placeholder="请输入IP地址" />
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-input v-model="cameraForm.location" placeholder="请输入摄像头位置" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="cameraForm.description" type="textarea" placeholder="请输入描述信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cameraDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCameraForm">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 视频流查看对话框 -->
    <el-dialog
      v-model="videoStreamDialogVisible"
      title="视频流查看"
      width="800px"
      fullscreen
    >
      <div class="video-stream-container">
        <div v-if="loadingStream" class="loading-stream">
          <el-loading text="正在加载视频流..." />
        </div>
        <video 
          v-else
          ref="videoPlayer"
          controls
          autoplay
          class="video-player"
        >
          您的浏览器不支持视频播放
        </video>
      </div>
      <template #footer>
        <el-button @click="closeVideoStream">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Camera, VideoCamera, Delete, Edit, Plus, Refresh, FullScreen, View, Close, Setting, VideoPlay } from '@element-plus/icons-vue'
import { api } from '../api/apiService'

export default {
  name: 'Cameras',
  components: {
    Plus,
    Setting,
    VideoPlay,
    View,
    Edit,
    // 移除Play引用
    Close,
    Delete
  },
  setup() {
    const loading = ref(false)
    const cameras = ref([])
    const cameraDialogVisible = ref(false)
    const cameraDialogType = ref('add')
    const videoStreamDialogVisible = ref(false)
    const loadingStream = ref(false)
    const videoPlayer = ref(null)
    const currentCameraId = ref(null)
    
    // 摄像头表单
    const cameraForm = reactive({
      id: '',
      name: '',
      rtsp_url: '',
      ip_address: '',
      location: '',
      description: ''
    })
    
    // 表单验证规则
    const cameraFormRules = {
      name: [
        { required: true, message: '请输入摄像头名称', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
      ],
      rtsp_url: [
        { required: true, message: '请输入RTSP地址', trigger: 'blur' }
      ],
      ip_address: [
        { required: true, message: '请输入IP地址', trigger: 'blur' },
        { 
          pattern: /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/, 
          message: '请输入有效的IP地址', 
          trigger: 'blur' 
        }
      ],
      location: [
        { required: true, message: '请输入摄像头位置', trigger: 'blur' }
      ]
    }
    
    // 获取摄像头列表
    const fetchCameras = async () => {
      try {
        loading.value = true
        // 注意：由于响应拦截器已经返回了response.data，这里直接使用返回值
        const camerasData = await api.cameras.getAllCameras()
        
        // 只使用后端返回的真实数据，不使用模拟数据
        if (camerasData && Array.isArray(camerasData)) {
          cameras.value = camerasData
        } else {
          cameras.value = []
          console.warn('后端未返回摄像头数据或数据格式不正确')
        }
      } catch (error) {
        console.error('获取摄像头列表失败:', error)
        cameras.value = []
        ElMessage.warning('无法获取摄像头数据，请检查后端服务')
      } finally {
        loading.value = false
      }
    }
    
    // 注意：不再使用模拟数据，仅从后端获取真实数据
    
    // 打开添加摄像头对话框
    const openAddCameraDialog = () => {
      cameraDialogType.value = 'add'
      resetCameraForm()
      cameraDialogVisible.value = true
    }
    
    // 编辑摄像头
    const editCamera = (camera) => {
      cameraDialogType.value = 'edit'
      Object.assign(cameraForm, camera)
      cameraDialogVisible.value = true
    }
    
    // 重置摄像头表单
    const resetCameraForm = () => {
      cameraForm.id = ''
      cameraForm.name = ''
      cameraForm.rtsp_url = ''
      cameraForm.ip_address = ''
      cameraForm.location = ''
      cameraForm.description = ''
    }
    
    // 提交摄像头表单
    const submitCameraForm = async () => {
      try {
        if (cameraDialogType.value === 'add') {
          await api.cameras.addCamera(cameraForm)
          ElMessage.success('摄像头添加成功')
        } else {
          await api.cameras.updateCamera(cameraForm.id, cameraForm)
          ElMessage.success('摄像头更新成功')
        }
        cameraDialogVisible.value = false
        fetchCameras()
      } catch (error) {
        console.error('操作摄像头失败:', error)
        ElMessage.error('操作失败，请重试')
      }
    }
    
    // 启动摄像头
    const startCamera = async (cameraId) => {
      try {
        await api.cameras.startCamera(cameraId)
        ElMessage.success('摄像头启动成功')
        fetchCameras()
      } catch (error) {
        console.error('启动摄像头失败:', error)
        ElMessage.error('启动失败，请重试')
      }
    }
    
    // 停止摄像头
    const stopCamera = async (cameraId) => {
      try {
        await api.cameras.stopCamera(cameraId)
        ElMessage.success('摄像头停止成功')
        fetchCameras()
      } catch (error) {
        console.error('停止摄像头失败:', error)
        ElMessage.error('停止失败，请重试')
      }
    }
    
    // 删除摄像头
    const deleteCamera = async (cameraId) => {
      try {
        await ElMessageBox.confirm('确定要删除该摄像头吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await api.cameras.deleteCamera(cameraId)
        ElMessage.success('摄像头删除成功')
        fetchCameras()
      } catch (error) {
        // 用户取消操作时不显示错误
        if (error !== 'cancel') {
          console.error('删除摄像头失败:', error)
          ElMessage.error('删除失败，请重试')
        }
      }
    }
    
    // 查看视频流
    const viewCameraStream = async (cameraId) => {
      currentCameraId.value = cameraId
      loadingStream.value = true
      videoStreamDialogVisible.value = true
      
      try {
        // 设置正确的视频流URL，使用后端提供的video_feed端点
        if (videoPlayer.value) {
          // 由于后端API服务运行在5001端口，使用正确的端口号
          videoPlayer.value.src = `http://localhost:5001/api/cameras/${cameraId}/video_feed`
          videoPlayer.value.load()
        }
      } catch (error) {
        console.error('加载视频流失败:', error)
        ElMessage.error('视频流加载失败')
      } finally {
        loadingStream.value = false
      }
    }
    
    // 关闭视频流
    const closeVideoStream = () => {
      videoStreamDialogVisible.value = false
      currentCameraId.value = null
      if (videoPlayer.value) {
        videoPlayer.value.pause()
        videoPlayer.value.src = ''
      }
    }
    
    // 页面挂载时获取摄像头列表
    onMounted(() => {
      fetchCameras()
    })
    
    return {
      loading,
      cameras,
      cameraDialogVisible,
      cameraDialogType,
      cameraForm,
      cameraFormRules,
      videoStreamDialogVisible,
      loadingStream,
      videoPlayer,
      openAddCameraDialog,
      editCamera,
      submitCameraForm,
      startCamera,
      stopCamera,
      deleteCamera,
      viewCameraStream,
      closeVideoStream
    }
  }
}
</script>

<style scoped>
.cameras-container {
  padding-bottom: 20px;
}

.page-card {
  margin-bottom: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
}

.cameras-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.camera-card {
  transition: all 0.3s;
}

.camera-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.camera-card.camera-offline {
  opacity: 0.6;
}

.camera-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.camera-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.camera-name {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.camera-preview {
  cursor: pointer;
}

.preview-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
  transition: transform 0.3s;
}

.preview-image:hover {
  transform: scale(1.02);
}

.camera-stats {
  margin-top: 10px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
  font-size: 14px;
}

.stat-label {
  color: #606266;
}

.stat-value {
  font-weight: 500;
}

.loading-container {
  padding: 20px;
}

.empty-state {
  padding: 40px 0;
}

.video-stream-container {
  height: calc(100vh - 200px);
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-player {
  max-width: 100%;
  max-height: 100%;
  border-radius: 4px;
}

.loading-stream {
  height: 400px;
  width: 100%;
}
</style>